<?php
/**
 * Created by PhpStorm.
 * User: xckj-lsp
 * Date: 2016/11/22
 * Time: 16:06
 */

namespace app\utils;


use yii\base\Exception;

class HttpUtil
{
    public static $responseHeader = array();
    public static $responseBody = array();
    public static $timeOut = 5;
    /**
     * @param $url
     * @param string $param
     * @param string $method
     * @param bool|FALSE $isShowHeader
     * @param string $cookie
     * @param string $refer
     * @param null|string $userAgent
     * @return string
     */
    static public function getHtml($url, $param = "", $method = 'GET', $isShowHeader = true, $cookie = NULL, $refer = null, $userAgent = null)
    {
        if(empty($url))
            return 0;
        @set_time_limit(0);
        $ch = curl_init();
        if ($isShowHeader) {
            curl_setopt($ch, CURLOPT_HEADER, 1); //是否显示头部信息
        }
//        empty($refer) && $refer ;
        $ua = $userAgent;
//        empty($ua) && $ua = $userAgent;
        curl_setopt($ch, CURLOPT_TIMEOUT, 5); //设置超时
        curl_setopt($ch, CURLOPT_USERAGENT, $ua); //用户访问代理 User-Agent
        curl_setopt($ch, CURLOPT_REFERER, $refer); //设置 referer
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); //跟踪301
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //返回结果
        if ($cookie != NULL) {
            curl_setopt($ch, CURLOPT_COOKIE, $cookie);
        }
        if (strtolower($method) == 'post') {
            curl_setopt($ch, CURLOPT_POST, TRUE);
            if ($param) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
            }
            curl_setopt($ch, CURLOPT_URL, $url);
        } else {
            curl_setopt($ch, CURLOPT_HTTPGET, TRUE);
            if ($param) {
                $urlInfo = parse_url($url);
                $q = array();
                if (isset($urlInfo['query']) && !empty($urlInfo['query'])) {
                    parse_str($urlInfo['query'], $q);
                }
                $q = array_merge($q, $param);
                $cUrl = sprintf('%s://%s%s%s%s',
                    $urlInfo['scheme'],
                    $urlInfo['host'],
                    isset($urlInfo['port']) ? ':' . $urlInfo['port'] : '',
                    isset($urlInfo['path']) ? $urlInfo['path'] : '',
                    count($q) ? '?' . http_build_query($q) : '');
                curl_setopt($ch, CURLOPT_URL, $cUrl);
            } else {
                curl_setopt($ch, CURLOPT_URL, $url);
            }
        }

        //新增https请求
        if(strstr($url,'https'))
        {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        }

        $ret = '';
        $r = curl_exec($ch);
        if ($isShowHeader) {
            $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
            $header = substr($r, 0, $headerSize);
            $body = substr($r, $headerSize);
            $ret = ['header' => $header, 'body' => $body];
        } else {
            $ret = $r;
        }
        curl_close($ch);
        unset($ch);
        return $ret;
    }

    static public function requestHttp($url,$data)
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_TIMEOUT, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $ret = curl_exec($ch);
        curl_close($ch);
        return $ret;
    }

    static public function get($url,$ua='')
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_TIMEOUT, 2);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if(!empty($ua)){
            curl_setopt($ch, CURLOPT_USERAGENT, $ua); //用户访问代理 User-Agent
        }
        //新增https请求
        if(strstr($url,'https'))
        {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        }
        $ret = curl_exec($ch);
        curl_close($ch);
        return $ret;
    }

    static public function curlProxy($url,$ua,$proxy){

        $ch = curl_init();
        curl_setopt ($ch, CURLOPT_URL, $url);
        curl_setopt ($ch, CURLOPT_USERAGENT, $ua);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt ($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt ($ch, CURLOPT_HEADER, 0);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
/*        curl_setopt ($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
        curl_setopt ($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC);*/
        curl_setopt ($ch, CURLOPT_HTTPPROXYTUNNEL, true);
        curl_setopt ($ch, CURLOPT_PROXY, $proxy);

        $result = curl_exec ($ch);
        curl_close($ch);
        return $result;

    }

    static public function requestApi($url,$data)
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_TIMEOUT, 2);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $ret = curl_exec($ch);
        curl_close($ch);
        return $ret;
    }

    static public function sendHttpsRequest($sendArr)
    {
        if(empty($sendArr))
            return false;
        if(!isset($sendArr['url']))
            return false;

        $ch = curl_init($sendArr['url']);

        //设置超时
        if(isset($sendArr['timeOut']) && $sendArr['timeOut'] > 0)
            curl_setopt($ch, CURLOPT_TIMEOUT, $sendArr['timeOut']);
        else
            curl_setopt($ch, CURLOPT_TIMEOUT, self::$timeOut);

        //跟踪301
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        //返回结果
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        //用户访问代理 User-Agent
        if(isset($sendArr['ua']))
            curl_setopt($ch, CURLOPT_USERAGENT, $sendArr['ua']);

        //设置 referer
        if(isset($sendArr['refer']))
            curl_setopt($ch, CURLOPT_REFERER, $sendArr['refer']);

        //是否显示头部信息
        if (isset($sendArr['isShowHeader']) && $sendArr['isShowHeader'] === true)
        {
            curl_setopt($ch, CURLOPT_HEADER, 1);
        }

        //设置cookie
        if(isset($sendArr['cookie']))
            curl_setopt($ch, CURLOPT_COOKIE, $sendArr['cookie']);

        //设置请求类型 默认get 只支持get与post
        if(isset($sendArr['method']) && strtolower($sendArr['method']) == 'post')
        {
            curl_setopt($ch, CURLOPT_POST, TRUE);
            if(isset($sendArr['params']))
                curl_setopt($ch, CURLOPT_POSTFIELDS, $sendArr['params']);
        }

        //设置header
        if(isset($sendArr['headers']))
            curl_setopt($ch, CURLOPT_HTTPHEADER, $sendArr['headers']);

        //设置https请求
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

        $responseStr = curl_exec($ch);
        if(isset($sendArr['isShowHeader']) && $sendArr['isShowHeader'] === true)
        {
            $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
            self::$responseHeader = substr($responseStr, 0, $headerSize);
            self::$responseBody = substr($responseStr, $headerSize);
        }
        else
            self::$responseBody = $responseStr;

        curl_close($ch);
        unset($ch);
        return true;
    }

    public static function getProxyHtml($gid)
    {
        $url = 'https://hws.m.taobao.com/cache/wdetail/5.0/?id=' . $gid;
//        $url = 'http://hws.bybyby.me/cache/wdetail/5.0/?id=' . $goods_id;

        $ip = PublicToolCode::RandIp();
        try {
            $http = new \GuzzleHttp\Client([
//              'base_uri'        => 'http://www.baidu.com',
                'timeout' => 8,
                'allow_redirects' => true,
                'headers' => [
                    'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:42.0) Gecko/20100101 Firefox/42.0',
                    'Accept-Encoding' => 'gzip, deflate, sdch, br',
                    //'X-Forwarded-For' => $ip,
                ],
                'proxy'           => 'http://xx.xx.11.xx:10088'
            ]);
            $data = $http->get($url)->getBody()->getContents();
        }catch (Exception $e){
            return false;
        }

        return $data;
    }
}